package com.m1book.site;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.m1book.domain.InviteService;
import com.m1book.domain.InviteTraceNotExistException;
import com.m1book.domain.relation.InviteTrace;

@RequestMapping("/relation")
@Controller
@SessionAttributes("inviteTrace")
public class JoinController {
	private static final Logger logger = LoggerFactory.getLogger(JoinController.class);
	
	@Autowired
	private InviteService inviteService;
	
	@RequestMapping(value = "/join", method = RequestMethod.GET)
	public String joinFromInvite(@RequestParam(required = true, value = "sn") String sn, Model model) {
		try {
			InviteTrace inviteTrace = inviteService.getInviteTrace(sn);
			model.addAttribute("inviteTrace", inviteTrace);
			model.addAttribute("invitee", inviteTrace.getInviteeName());
			model.addAttribute("inviter", inviteTrace.getInviter().getInfo().getRealname());
			model.addAttribute("inviterid", inviteTrace.getInviter().getId().toString());
			logger.info("join by invite trace: " + inviteTrace.toString());
		} catch (InviteTraceNotExistException e) {
			logger.warn(e.getMessage());
			model.addAttribute("reason", "[" + sn + "]不存在。");
			return "/relation/joinfailed";
		}
		
		return "/relation/joinsucceed";
	}

}
